<template>
  <edit-layout ref="layout" :page="page" :form="form" @invoke="invoke">
    <el-form ref="form" :model="form" :size="page.settings.formSize" :label-width="page.settings.labelWidth">
      <div v-if="form!=null && form.id==null">
        <el-form-item label="业务员" prop="salesmanId" :rules="page.rules.def">
          <duty-users v-model="form.salesmanId" :duty-id="$store.state.settings.wmsConf.purchase.dutyId[1]" @change="salesmanChange" />
        </el-form-item>
        <el-form-item v-show="form.salesmanId!=null" label="供应商" prop="supplierId" :rules="page.rules.def">
          <form-remote-select
            ref="supplier"
            v-model="form.supplierId"
            @change="supplierChange"
          />
        </el-form-item>
        <el-form-item v-if="form.supplierId" label="收款信息" prop="bankId">
          <supplier-bank ref="bank" v-model="form.bankId" :supplier-id="form.supplierId" />
        </el-form-item>
        <el-form-item label="纸厂" prop="destinationId" :rules="page.rules.def">
          <form-remote-select
            v-model="form.destinationId"
            :url="service.conf.api.get('wms').url+'/api/logistics/location/map'"
          />
        </el-form-item>

        <el-form-item label="订单备注" prop="remark">
          <el-input v-model="form.remark" class="col-6" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </div>
      <div v-if="form.id!=null">
        <div class="order-steps">
          <el-steps v-if="form.status!=6 && form.status!=7" :active="status" finish-status="success" align-center>
            <el-step title="待发货" />
            <el-step title="待收货" />
            <el-step title="待定价" />
            <el-step title="待核算" />
            <el-step title="待审批" />
            <el-step title="待结算" />
          </el-steps>
        </div>
        <el-divider content-position="left">基本信息</el-divider>
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="采购单号：">
              <label>{{ form.no }}</label>
              <el-tag :type="orderStatus.type" size="mini" effect="plain">{{ orderStatus.label }}</el-tag>
              <el-tag v-if="form.flag>0" size="mini" effect="plain" type="danger">{{ constants.supOrderFlag.get(form.flag).label }}</el-tag>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="业务员：">
              <employee-card v-model="form.salesman" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接货员：">
              <employee-card v-model="form.consignee" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出纳：">
              <employee-card v-model="form.cashier" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="采购量：">
              <label><span class="money">{{ form.quantity.toFixed(3) }}</span> 吨</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="验收量：">
              <label><span class="money">{{ form.settleQuantity.toFixed(3) }}</span> 吨</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="打包数：">
              <label><span class="money">{{ form.packages }}</span> 包</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="供货金额：">
              <label class="money">￥{{ form.totalAmount.toFixed(2) }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结算金额：">
              <label class="money">￥{{ form.actualAmount.toFixed(2) }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="扣点金额：">
              <label class="money">￥{{ form.deductAmount.toFixed(2) }}</label>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="创建人：">
              <label>{{ form.creator }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间：">
              <label>{{ form.createTime }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="更新时间：">
              <label>{{ form.updateTime }}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="form.remark" class="col-6" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
        <el-divider content-position="left">发货信息</el-divider>
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="发货点：">
              <label>{{ form.startLocation.name }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发货人：">
              <label>{{ form.startLocation.linkman }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式：">
              <label>{{ form.startLocation.mobile }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="发货地址：">
              <label>{{ form.startLocation.area }}{{ form.startLocation.address }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="license" label="车牌号：">
              <label>{{ license }}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">收货信息</el-divider>
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="收货点：">
              <label>{{ form.endLocation.name }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货人：">
              <label>{{ form.endLocation.linkman }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式：">
              <label>{{ form.endLocation.mobile }}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-bg">
          <el-col :span="16">
            <el-form-item label="详细地址：">
              <label>{{ form.endLocation.area }}{{ form.endLocation.address }}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <pur-extend ref="purExtend" />
      </div>
      <div class="details">
        <el-tabs value="detail" type="border-card">
          <el-tab-pane label="货品明细" name="detail">
            <div class="bg" />
            <table v-if="form.details" cellspacing="0" cellpadding="0">
              <thead>
                <tr>
                  <th class="index">#</th>
                  <th class="tool" valign="middle"><el-button class="btn" size="mini" icon="el-icon-plus" @click="plus" /></th>
                  <th>货品</th>
                  <th>供货量(吨)</th>
                  <th>打包数</th>
                  <th>扣点(%)</th>
                  <th>扣点重量(吨)</th>
                  <th style="text-align:center">结算量(吨)</th>
                  <th style="text-align:right">单价/吨</th>
                  <!-- <th style="text-align:right">采购小计</th> -->
                  <th style="text-align:right">结算小计</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in form.details " :key="index">
                  <td class="index">{{ index+1 }}</td>
                  <td class="tool">
                    <el-button size="small" class="btn" icon="el-icon-minus" @click="minus(index)" />
                  </td>
                  <td>
                    <el-form-item :prop="'details.' + index + '.productId'" :rules="page.rules.def" label-width="0px">
                      <form-remote-select
                        v-if="form.status<=1"
                        v-model="item.productId"
                        size="mini"
                        :url="service.conf.api.get('wms').url+'/api/gds/product-info/map/1/'"
                        @change="(current)=>bindProduct(current,item)"
                      />
                      <label v-if="form.status>1">{{ item.name }}</label>
                    </el-form-item>
                  </td>
                  <td>
                    <el-form-item :prop="'details.' + index + '.quantity'" :rules="page.rules.num" label-width="0px">
                      <el-input-number v-if="form.status<=1" v-model="item.quantity" size="mini" controls-position="right" :precision="3" :min="0" @change="(c,o)=>calQuantityItem(item)" />
                      <label v-if="form.status>1">{{ item.quantity.toFixed(3) }}</label>
                    </el-form-item>
                  </td>
                  <td style="text-align:center">
                    <el-form-item :prop="'details.' + index + '.packages'" :rules="page.rules.num" label-width="0px">
                      <el-input-number v-if="form.status<=1" v-model="item.packages" size="mini" controls-position="right" :min="1" @change="(c,o)=>calItem(item)" />
                      <label v-if="form.status>1">{{ item.packages }}</label>
                    </el-form-item>
                  </td>
                  <td style="text-align:center">
                    <el-form-item :prop="'details.' + index + '.deduct'" :rules="page.rules.num" label-width="0px">
                      <el-input-number v-if="form.status==1" v-model="item.deduct" size="mini" controls-position="right" :precision="3" :max="100" :min="0" @change="(c,o)=>calDeductItem(item)" />
                      <label v-if="form.status!=1">{{ item.deduct.toFixed(3) }}</label>
                    </el-form-item>
                  </td>
                  <td style="text-align:center" :prop="'details.' + index + '.deductQuantity'">
                    <el-form-item :prop="'details.' + index + '.deductQuantity'" :rules="page.rules.num" label-width="0px">
                      <el-input-number v-if="form.status==1" v-model="item.deductQuantity" size="mini" controls-position="right" :precision="3" :max="item.quantity" :min="0" @change="(c,o)=>calDeductWeightItem(item)" />
                      <label v-if="form.status!=1">{{ item.deductQuantity.toFixed(3) }}</label>
                    </el-form-item>
                  </td>
                  <td style="text-align:center" :prop="'details.' + index + '.settleQuantity'">
                    <el-form-item :prop="'details.' + index + '.settleQuantity'" :rules="page.rules.num" label-width="0px">
                      <el-input-number v-if="form.status==1" v-model="item.settleQuantity" size="mini" controls-position="right" :precision="3" :max="item.quantity" :min="0" @change="(c,o)=>calSettleItem(item)" />
                      <label v-if="form.status!=1">{{ item.settleQuantity.toFixed(3) }}</label>
                    </el-form-item>
                  </td>
                  <td>
                    <el-form-item :prop="'details.' + index + '.price'" :rules="page.rules.num" label-width="0px">
                      <el-input-number v-if="form.status==2" v-model="item.price" size="mini" controls-position="right" :precision="2" :min="0" @change="(c,o)=>calItem(item)" />
                      <label v-if="form.status!=2" class="money">￥{{ item.price.toFixed(2) }}</label>
                    </el-form-item>
                  </td>
                  <!-- <td>
                    <el-form-item :prop="'details.' + index + '.money'" :rules="page.rules.num" label-width="0px">
                      <label class="money">￥{{ item.money.toFixed(2) }}</label>
                    </el-form-item>
                  </td> -->
                  <td>
                    <el-form-item :prop="'details.' + index + '.settleMoney'" :rules="page.rules.num" label-width="0px">
                      <label class="money">￥{{ item.settleMoney.toFixed(2) }}</label>
                    </el-form-item>
                  </td>
                </tr>
              </tbody>
            </table>
          </el-tab-pane>
          <el-tab-pane v-if="form.id!=null" label="操作日志" name="log">
            <logs ref="logs" @call="callLogs" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-form>
    <div v-if="form.id!=null" class="action">
      <pur-checking v-if="form.status===0" ref="checking" v-model="form.id" :self="self" />
      <pur-eceiving v-if="form.status===1" ref="eceiving" v-model="form.id" :self="self" />
      <pur-pricing v-if="form.status===2" ref="pricing" v-model="form.id" :order-price="form.totalAmount" :self="self" />
      <pur-adjusting v-if="form.status===3" ref="adjusting" v-model="form.id" :order-price="form.actualAmount" :self="self" />
      <pur-reject v-if="form.status<5" ref="reject" v-model="form.id" :self="self" />
      <pur-canceling v-if="form.status<5" ref="canceling" v-model="form.id" :self="self" />
      <pur-paying v-if="form.status===4" ref="paying" v-model="form.id" :self="self" />
      <pur-replying v-if="form.status===10" ref="replying" v-model="form.id" :self="self" />
      <pur-returning v-if="form.status===1" ref="returning" v-model="form.id" :self="self" />
      <edit-location v-if="form.id!=null && form.status<5" ref="editLocation" :self="self" />
    </div>
  </edit-layout>
</template>
<script>
import adminSupport from 'lola-admin-support-el'
import logs from '@/views/pur-group/order-manage/logs.vue'
import SupplierBank from '@/components/SupplierBank'

import PurChecking from '@/views/pur-group/order-manage/components/checking.vue'
import PurEceiving from '@/views/pur-group/order-manage/components/eceiving.vue'
import PurPricing from '@/views/pur-group/order-manage/components/pricing.vue'
import PurAdjusting from '@/views/pur-group/order-manage/components/adjusting.vue'
import PurReplying from '@/views/pur-group/order-manage/components/replying.vue'
import PurReject from '@/views/pur-group/order-manage/components/reject.vue'
import PurCanceling from '@/views/pur-group/order-manage/components/canceling.vue'
import PurPaying from '@/views/pur-group/order-manage/components/paying.vue'
import EditLocation from '@/views/pur-group/order-manage/components/edit-location.vue'
import PurExtend from '@/views/pur-group/order-manage/components/extend.vue'
import PurReturning from '@/views/pur-group/order-manage/components/returning.vue'

export default {
  name: 'PurOrderManageEdit',
  components: {
    logs,
    PurChecking,
    PurEceiving,
    PurPricing,
    PurAdjusting,
    PurReject,
    PurCanceling,
    PurPaying,
    EditLocation,
    PurReturning,
    SupplierBank,
    PurExtend,
    PurReplying
  },
  mixins: [adminSupport.mixins.edit],
  data() {
    return {
      name: 'PurOrderManage',
      orderStatus: null,
      status: 0,
      self: null,
      settleQuantity: 0,
      license: null
    }
  },
  mounted() {
    this.init()// 初始化
  },
  methods: {
    init() {
      const that = this
      this.self = that
      that.page.tip = '请认真核对业务员/供应商/纸厂相关选项,创建后禁止修改!'
      that.page.ids.push(this.$route.params.no)// 页面主参数赋值
      that.loadData()// 加载数据
    },
    appendForm() {
      this.orderStatus = this.$constants.supOrderStatus.get(this.form.status)
      if (this.form.status > 3 && this.form.status !== 10) {
        this.status = this.form.status + 1
      } else {
        this.status = this.form.status
      }
      if (this.form.status === 10) {
        this.status = 4
      }
      // alert(this.status)
      this.settleQuantity = this.form.settleQuantity
      if (this.form.id != null) {
        setTimeout(() => {
          this.$refs.logs.load(this.form.id)
        }, 1000)
      }
      // console.log(this.orderStatus)
    }, buildForm() {
      return true
    },
    plus() { // 添加明细
      this.form.details.push({ money: 0, quantity: 0, price: 0, deduct: 0, deductQuantity: 0, packages: 0, settleMoney: 0, settleQuantity: 0 })
      // console.log(this.form.details)
    },
    minus(index) { // 删除明细
      this.form.details.splice(index, 1)
    },
    callLogs(orderLogs) {
      // console.log(orderLogs)
      this.$refs.purExtend.load(orderLogs, this.form)
      const shipments = orderLogs.filter(o => o.action === 1)
      if (shipments != null && shipments.length > 0) {
        const log = shipments[shipments.length - 1]
        const json = JSON.parse(log.extendJson)
        this.license = json.license
      }
    },
    supplierChange(current) {
      console.log(current)
    },
    salesmanChange(current) {
      const url = this.service.conf.api.get('wms').url + '/api/sup/supplier-info/map/' + this.form.salesmanId
      this.$refs['supplier'].reload('', url)
    },
    bindProduct(current, item) {
      item.productNo = current.val
      item.name = current.name
    },
    calQuantityItem(item) {
      this.calDeductItem(item)
    },
    calSettleItem(item) {
      // 扣点重量= 采购量-结算重量
      item.deductQuantity = item.quantity - item.settleQuantity
      // 扣点率 （采购量-结算量）/采购量*100
      item.deduct = item.deductQuantity / item.quantity * 100
      this.calItem(item)
    },
    calDeductWeightItem(item) {
      // 扣点率=扣点重量/采购量
      item.deduct = item.deductQuantity / item.quantity * 100
      // 结算重量=采购量-扣点重量
      item.settleQuantity = item.quantity - item.deductQuantity
    },
    calDeductItem(item) {
      console.log(item.deduct)
      // 扣点重量=采购重量*扣点率
      item.deductQuantity = item.quantity * item.deduct / 100
      // 结算重量=采购量-扣点重量
      item.settleQuantity = item.quantity - item.deductQuantity
      this.calItem(item)
    },
    calItem(item) {
      // 计算小计
      item.money = item.quantity * item.price
      item.settleMoney = item.settleQuantity * item.price
      this.cal()
    },
    cal() {
      // 计算订单总额
      let quantity = 0 // 订单采购量
      let settleQuantity = 0 // 结算量
      let totalAmount = 0 // 采购总金额
      let actualAmount = 0 // 结算金额
      this.form.details.forEach(item => {
        quantity += item.quantity
        settleQuantity += item.settleQuantity
        totalAmount += item.money
        actualAmount += item.settleMoney
      })
      this.form.quantity = quantity
      this.form.settleQuantity = settleQuantity
      this.form.totalAmount = totalAmount
      this.form.actualAmount = actualAmount
      if (this.form.settleQuantity > 0) {
        this.form.deductQuantity = this.form.quantity - this.form.settleQuantity
        this.form.deductAmount = this.form.totalAmount - this.form.actualAmount
      }
    },
    buildOtherBtn(item, btn) { // 调整权限按钮
      switch (item.code) {
        case 'm0000': // 保存
        {
          btn.disable = this.form.status < 5
          break
        }
        case 'm5252': // 删除
          btn.disable = this.form.status === 0 && this.form.id !== null
          break
        case 'm5255': // 修改发货信息
          btn.disable = this.form.status === 0 && this.form.id !== null
          btn.opt = 'editStartLocation'
          break
        case 'm5256': // 修改收货信息
          btn.disable = this.form.status === 0 && this.form.id !== null
          btn.opt = 'editEndLocation'
          break
        case 'm52596': // 修改收货信息
          btn.disable = this.form.status > 0 && this.form.status < 5
          btn.opt = 'notification'
          break
        case 'm5257': // 驳回
        {
          btn.disable = this.form.status < 5 && this.form.id !== null
          btn.type = 'danger'
          btn.opt = 'reject'
          break
        }
        case 'm5258': // 发货
        {
          btn.disable = this.form.status === 0 && this.form.id !== null
          btn.opt = 'checking'
          break
        }
        case 'm5259': // 收货
        {
          btn.disable = this.form.status === 1 && this.form.id !== null
          btn.opt = 'eceiving'
          break
        }
        case 'm52591': // 定价
        {
          btn.disable = this.form.status === 2 && this.form.id !== null
          btn.opt = 'pricing'
          break
        }
        case 'm52592': // 核算
        {
          btn.disable = this.form.status === 3 && this.form.id !== null
          btn.opt = 'adjusting'
          break
        }
        case 'm52595': // 结算
        {
          btn.disable = this.form.status === 4 && this.form.id !== null
          btn.opt = 'payment'
          break
        }
        case 'm52593': // 取消
        {
          btn.disable = this.form.status === 0 && this.form.id !== null
          btn.type = 'danger'
          btn.opt = 'canceling'
          break
        }
        case 'm52594': // 退货
        {
          btn.disable = this.form.status === 1 && this.form.id !== null
          btn.type = 'warning'
          btn.opt = 'returning'
          break
        }
        case 'm52597': // 退货
        {
          btn.disable = this.form.status === 7
          btn.type = 'danger'
          btn.opt = 'recycle'
          break
        }
        case 'm52598': // 核算批复
        {
          btn.disable = this.form.status === 10
          btn.opt = 'replying'
          break
        }
      }
      // console.log(btn)
    },
    checking() { // 发货操作
      this.$refs.checking.show()
    },
    eceiving() { // 收货确认
      if (this.settleQuantity === 0) {
        this.$message.error('请保存结算量后,进行操作!')
        return
      }
      // alert(this.form.deduct)
      this.$refs.eceiving.show(this.form.deductQuantity, this.form.deduct)
    },
    pricing() { // 定价
      if (this.form.totalAmount === 0) {
        this.$message.error('请保存货品单价后,进行操作!')
        return
      }
      this.$refs.pricing.show(this.form.totalAmount, this.form.actualAmount)
    },
    adjusting() { // 核算
      this.$refs.adjusting.show(this.form.paymentAmount)
    },
    replying() { // 核算审批
      this.$refs.replying.show(this.form.paymentAmount)
    },
    reject() { // 订单驳回
      this.$refs.reject.show()
    },
    canceling() { // 取消订单
      this.$refs.canceling.show()
    },
    payment() { // 结算
      this.$refs.paying.show(this.form.paymentAmount, this.form.bankId, this.form.flag)
    },
    editStartLocation() { // 修改发货信息
      this.$refs.editLocation.show(this.form.startLocation, '修改发货信息')
    },
    editEndLocation() { // 修改收货信息
      this.$refs.editLocation.show(this.form.endLocation, '修改收货信息')
    },
    returning() {
      this.$refs.returning.show()
    },
    notification() {
      const that = this
      const loading = that.$loading()
      const url = that.page.router.remoteUrl + '/notification/' + that.form.id
      that.self.service.get(url).then(res => {
        loading.close()
        if (res.code !== 200) {
          that.$message.error(res.message)
          return
        }
        that.$message.success('操作成功!')
      }).catch((e) => {
        loading.close()
      })
    },
    recycle() {
      const that = this
      const loading = that.$loading()
      const url = that.page.router.remoteUrl + '/recycle/' + that.form.id
      that.self.service.get(url).then(res => {
        loading.close()
        if (res.code !== 200) {
          that.$message.error(res.message)
          return
        }
        that.$message.success('操作成功!')
        that.close()
      }).catch((e) => {
        loading.close()
      })
    }
  }
}
</script>
<style scoped>
.order-steps{
  padding-top: 20px;
  padding-bottom: 20px;
  clear: both;
}
</style>
